import { defineStore } from 'pinia'
import { ref, computed } from 'vue'  // 添加 computed 导入

export const useUserStore = defineStore('user', () => {
  // 从 localStorage 初始化用户状态
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
  const token = ref(localStorage.getItem('token') || null)
  
  // 添加计算属性
  const isLoggedIn = computed(() => !!user.value)
  
  const login = async (credentials) => {
    try {
      // 模拟登录API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 模拟返回的用户数据
      const userData = {
        id: Date.now(),
        username: credentials.username,
        email: `${credentials.username}@example.com`
      }
      
      const userToken = 'mock-jwt-token-' + Date.now()
      
      // 更新状态
      user.value = userData
      token.value = userToken
      
      // 保存到 localStorage
      localStorage.setItem('user', JSON.stringify(userData))
      localStorage.setItem('token', userToken)
      
      console.log('登录成功:', userData)
      return userData
    } catch (error) {
      console.error('登录失败:', error)
      throw new Error('登录失败，请检查用户名和密码')
    }
  }
  
  const register = async (userData) => {
    try {
      // 模拟注册API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 检查用户名是否已存在（模拟）
      const existingUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
      const userExists = existingUsers.some(u => u.username === userData.username)
      
      if (userExists) {
        throw new Error('用户名已存在')
      }
      
      // 保存注册用户信息
      const newUser = {
        id: Date.now(),
        username: userData.username,
        email: userData.email,
        password: userData.password // 注意：实际项目中密码应该哈希存储
      }
      
      existingUsers.push(newUser)
      localStorage.setItem('registeredUsers', JSON.stringify(existingUsers))
      
      console.log('注册成功:', newUser)
      return newUser
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  }
  
  const logout = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('user')
    localStorage.removeItem('token')
    console.log('已退出登录')
  }
  
  // 检查登录状态
  const checkAuth = () => {
    const savedUser = localStorage.getItem('user')
    const savedToken = localStorage.getItem('token')
    
    if (savedUser && savedToken) {
      user.value = JSON.parse(savedUser)
      token.value = savedToken
      return true
    }
    return false
  }
  
  return { 
    user, 
    token, 
    login, 
    register, 
    logout, 
    checkAuth,
    isLoggedIn  // 添加这个计算属性
  }
})